package com.jzg.jcptadmin.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.app.UpdateManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CityItem;
import com.jzg.jcptadmin.data.vo.IndexData;
import com.jzg.jcptadmin.data.vo.NewStyle;
import com.jzg.jcptadmin.data.vo.TotalCountInfo;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.data.vo.WorkInfo;
import com.jzg.jcptadmin.presenter.HomePresenter;
import com.jzg.jcptadmin.view.ProgressView;
import com.jzg.jcptadmin.viewinterface.HomeActivityInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.jzg.template.refreshrecycleview.RecycleViewBaseAdapter;
import com.umeng.analytics.MobclickAgent;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 主页
 * HomeActivity
 *
 * @author sunbl
 *         created at 2016/1/22 11:24
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener, HomeActivityInterface {
    private static final int REQUECT_CODE_SDCARD = 1;
    @Bind(R.id.view1)
    ProgressView view1;
    @Bind(R.id.view2)
    ProgressView view2;
    @Bind(R.id.gridview)
    RecyclerView gridview;
    @Bind(R.id.kaiguan)
    ImageView kaiguan;
    @Bind(R.id.ivCanpei)
    ImageView ivCanpei;
//    @Bind(R.id.ceshi)
//    TextView ceshi;


    private List<IndexData> mData;
    private HomePresenter homePresenter;
    //首页选项适配
    private GridViewAdapter gridViewAdapter;
//    //程序是否退出标记 true退出 false不退出
//    private static Boolean isExit = false;
    private User user;
    private String[] youmeng = new String[]{"pinggushi_jishipinggu", "pinggushi_xianshangpinggu", "pinggushi_xianxiapinggu", "pinggushi_shezhi"};//友盟统计埋点
    private CityItem cityItem;
    private int mPosition =0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
//        ceshi.setText("测试版本"+"1.0");
        user = appContext.getUser();
        if (user.getIsShowDaKa() == 0) {
            kaiguan.setVisibility(View.GONE);
        } else {
            if (user.getIsWork() == 0) {//下班状态
                kaiguan.setImageResource(R.drawable.off);
            } else {//上班状态
                kaiguan.setImageResource(R.drawable.on);
            }
        }
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        homePresenter = new HomePresenter(DataManager.getInstance());
        homePresenter.attachView(this);
        if (!MPermissions.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUECT_CODE_SDCARD)) {
            MPermissions.requestPermissions(this, REQUECT_CODE_SDCARD, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        } else {
            appContext.initFile();
        }
        //检查新版本
        if (AppContext.isNetWork)
            UpdateManager.getUpdateManager().checkAppUpdate(this, false);

        ininData();
//        JPushInterface.resumePush(getApplicationContext());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @PermissionGrant(REQUECT_CODE_SDCARD)
    public void requestSdcardSuccess() {
        appContext.initFile();
    }

    @PermissionDenied(REQUECT_CODE_SDCARD)
    public void requestSdcardFailed() {
        MyToast.showShort("授权被拒!");
    }

    @Override
    protected void onResume() {
        super.onResume();
        homePresenter.loadCount();
    }

    private void ininData() {
        view1.setData(0, 0, "快速线上检测", 0xffFA6269);
        view2.setData(0, 0, "专业线下检测", 0xff37BF9B);
//        view3.setData("8", "/10", "专业线上检测", 0xff37BF9B, 8 * 100 / 10);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridview.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        gridview.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL));
        gridview.setLayoutManager(gridLayoutManager);
        mData = new ArrayList<>();
        mData.add(new IndexData("即时系统评估", R.drawable.zoom, TimelyEstimateActivity.class));
        mData.add(new IndexData("快速线上评估", R.drawable.file, KuaiSuOnLineActivity.class));
        mData.add(new IndexData("专业线下评估", R.drawable.clipboard, OfflineDetectionActivity.class));
        if ("1".equals(user.getAgentStatistics())) {
            mData.add(new IndexData("订单统计", R.drawable.dingdan03, OrderStatisticsActivity.class));
        }
        if ("1".equals(user.getPGSStatistics())) {
            mData.add(new IndexData("评估师统计", R.drawable.pinggushi03, AppraisersStatisticsActivity.class));
        }
        if ("1".equals(user.getAgentStatistics())) {
            mData.add(new IndexData("机构统计", R.drawable.jigou03, OrganizationStatisticsActivity.class));
        }
        mData.add(new IndexData("设置", R.drawable.settings, SystemSetActivity.class));
        gridViewAdapter = new GridViewAdapter();
        gridViewAdapter.setOnItemClickLitener(new RecycleViewBaseAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                mPosition = position;
                if(mData.size()==4){
                    MobclickAgent.onEvent(HomeActivity.this, youmeng[position]);//友盟统计
                }else if(mData.size()==5){
                    if(position==4){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position-1]);//友盟统计
                    }else if(position!=3){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position]);//友盟统计
                    }
                }else if(mData.size()==6){
                    if(position==5){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position-2]);//友盟统计
                    }else if(position!=3&&position!=4){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position]);//友盟统计
                    }
                }else if(mData.size()==7){
                    if(position==6){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position-3]);//友盟统计
                    }else if(position!=3&&position!=4&&position!=5){
                        MobclickAgent.onEvent(HomeActivity.this, youmeng[position]);//友盟统计
                    }
                }
                if(mData.size()>4&&position!=6&&position>2){
                        if(cityItem!=null){
                            Intent intent1 = new Intent(HomeActivity.this, mData.get(position).getaClass());
                            intent1.putExtra(Constant.ACTIVITY_CITYITEM,cityItem);
                            startActivity(intent1);
                        }else{
                            showDialog();
                            homePresenter.getCityData(getCityDataParams());
                        }
                }else {
                    Intent intent = new Intent(HomeActivity.this, mData.get(position).getaClass());
                    startActivity(intent);
                }
            }
        });
        gridview.setAdapter(gridViewAdapter);
    }

    @OnClick({R.id.view1, R.id.view2, R.id.kaiguan,R.id.ivCanpei})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view1:  //线上
                ActivityHelp.startActivity(this, KuaiSuOnLineActivity.class);
                MobclickAgent.onEvent(HomeActivity.this, "pinggushi_xianshangtu");//友盟统计
                break;
            case R.id.view2:  //线下
                ActivityHelp.startActivity(this, OfflineDetectionActivity.class);
                MobclickAgent.onEvent(HomeActivity.this, "pinggushi_xianxiatu");//友盟统计
                break;
            case R.id.kaiguan:
                showDialog();
                homePresenter.getWork();//点击上下班
                MobclickAgent.onEvent(HomeActivity.this, "pinggushi_shangxiban");//友盟统计
            case R.id.ivCanpei:
                break;
            default:
                break;
        }
    }

    @Override
    public void success(@NonNull TotalCountInfo totalCountInfo) {
        if (totalCountInfo.getStatus() == Constant.SUCCESS) {
            view1.update(totalCountInfo.getTaskCount1_2(), totalCountInfo.getTaskCount1_1() + totalCountInfo.getTaskCount1_2());
            view2.update(totalCountInfo.getTaskCount3_2(), totalCountInfo.getTaskCount3_1() + totalCountInfo.getTaskCount3_2());
//            if (user.getXSDJbol() == 1) {//用于添加任务的权限
//                mData.get(2).setCount(totalCountInfo.getReplyCount1());//设置快速线上数目
//                mData.get(3).setCount(totalCountInfo.getReplyCount2());//设置专业线下数目
//            }else{
//                mData.get(1).setCount(totalCountInfo.getReplyCount1());//设置快速线上数目
//                mData.get(2).setCount(totalCountInfo.getReplyCount2());//设置专业线下数目
//            }
            gridViewAdapter.notifyDataSetChanged();
        } else {
            MyToast.showShort(totalCountInfo.getMsg());
        }

    }

    @Override
    public void successForwork(WorkInfo info) {
        dismissDialog();
        if (info.getStatus() == 100) {
            if (info.getIsWork() == 0) {//下班状态
                kaiguan.setImageResource(R.drawable.off);
            } else {//上班状态
                kaiguan.setImageResource(R.drawable.on);
            }
        } else {
            MyToast.showShort("打卡失败！");
        }
    }

    /**
     * 获取消息总数参数
     *
     * @return
     */
    @NonNull
    @Override
    public Map<String, String> getTotalCountParams() {
        Map<String, String> params = new HashMap<>();
        params.put("userid", String.valueOf(user.getUserId()));
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    @NonNull
    @Override
    public Map<String, String> getWorkParams() {
        Map<String, String> params = new HashMap<>();
        params.put("userid", String.valueOf(user.getUserId()));
        params.put("op", "onwork");
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    @Override
    public void cityDataSuccess(CityItem cityItem) {
        dismissDialog();
        if(cityItem.getStatus()==100){
            this.cityItem = cityItem;
            Intent intent2 = new Intent(HomeActivity.this, mData.get(mPosition).getaClass());
            intent2.putExtra(Constant.ACTIVITY_CITYITEM,cityItem);
            startActivity(intent2);
        }

    }

    private Map<String, String> getCityDataParams() {
        Map<String, String> params = new HashMap<>();
        params.put("tokenid", "6");
        params.put("UserID", user.getUserId() + "");
        Map<String, Object> signMaps = new HashMap<>();
        signMaps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMaps));
        return params;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
        if (homePresenter != null)
            homePresenter.detachView();
    }

    @Override
    public void showError(String error) {
        dismissDialog();
        MyToast.showShort( Constant.errr_net);
    }

    /**
     * Home页item项适配
     */
    class GridViewAdapter extends RecycleViewBaseAdapter {
        //        void interface
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(getLayoutInflater().inflate(R.layout.grid_item, null));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            MyViewHolder molder = (MyViewHolder) holder;
            molder.tv.setText(mData.get(position).getString());
            Drawable drawable = getResources().getDrawable(mData.get(position).getImage());
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            molder.tv.setCompoundDrawables(null, drawable, null, null);
            if (user.getXSDJbol() == 1) {
                if (position == 2) {
                    molder.online.setVisibility(View.VISIBLE);
                }
            } else {
                if (position == 1) {
                    molder.online.setVisibility(View.VISIBLE);
                }
            }


            if (mData.get(position).getCount() == 0) {
                molder.dragtext.setVisibility(View.GONE);
            } else {
                molder.dragtext.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.name_text)
            TextView tv;
            @Bind(R.id.dragtext)
            ImageView dragtext;
            @Bind(R.id.online)
            ImageView online;

            public MyViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
//                tv = (TextView) view.findViewById(R.id.name_text);
//                dragtext = (ImageView) view.findViewById(R.id.dragtext);
//                online = (ImageView) view.findViewById(R.id.online);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return false;
    }

    //TODO 参配信息测试 完毕后删除
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NewStyle newStyle) {
        if(newStyle==null){
            return;
        }else{
            if(newStyle.isCancel()){
                return;
            }
            AppManager.getAppManager().finishActivity(AdmixedContrastActivity.class);

            MyToast.showShort(newStyle.getName()+" "+newStyle.getYear()+"款"+Double.valueOf(newStyle.getNowMsrp()) +"万元");

//            localCarConfigModel.setStyleId(Integer.valueOf(newStyle.getStyleId()));
//            localCarConfigModel.setStyleName(newStyle.getName());
//            localCarConfigModel.setNowMsrp(Double.valueOf(newStyle.getNowMsrp()));
//            localCarConfigModel.setFullName(newStyle.getName()+" "+newStyle.getYear()+"款"+Double.valueOf(newStyle.getNowMsrp()) +"万元");
//            tvTitle.setText(localCarConfigModel.getFullName());
        }
    }
}
